package org.stayfool.client.session;

import org.stayfool.client.MqttOption;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by stayfool on 2016/12/5.
 */
public final class SessionManager {

    private static final ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    private SessionManager() {
    }

    public static <K, V> Session<K, V> init(MqttOption option) {

        Session s;
        try {
            s = option.session().newInstance();
        } catch (InstantiationException
                | IllegalAccessException
                | NullPointerException e) {
            // default
            s = new MemorySession();
        }
        return sessionMap.putIfAbsent(option.clientId(), s);
    }

    /**
     * 获取已存在的Session
     * <p>
     * 不存在则为当前 {@code clientId} 创建一个{@code Session}
     * <p>
     * 默认使用{@link MemorySession}
     *
     * @param clientId clientId
     * @return Session
     */
    public static <K, V> Session<K, V> getSession(String clientId) {
        return sessionMap.get(clientId);
    }

    /**
     * 清除Session
     *
     * @param clientId clientId
     */
    public static <K, V> Session<K, V> removeSession(String clientId) {
        return sessionMap.remove(clientId);
    }

}
